using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace LTKJ.RTU
{
    /// <summary>
    /// 性能监控器 - 实时监控系统资源使用情况
    /// </summary>
    public class PerformanceMonitor : IDisposable
    {
        private readonly Timer monitorTimer;
        private readonly Process currentProcess;
        private volatile bool isDisposed = false;
        
        // 性能指标
        public long CurrentMemoryUsageMB { get; private set; }
        public double CurrentCpuUsage { get; private set; }
        public int CurrentThreadCount { get; private set; }
        public int CurrentHandleCount { get; private set; }
        
        // 历史数据
        public long PeakMemoryUsageMB { get; private set; }
        public double PeakCpuUsage { get; private set; }
        public int PeakThreadCount { get; private set; }
        
        // 事件
        public event Action<string> OnPerformanceAlert;
        public event Action<PerformanceMetrics> OnMetricsUpdated;
        
        public PerformanceMonitor()
        {
            currentProcess = Process.GetCurrentProcess();
            monitorTimer = new Timer(CollectMetrics, null, 1000, 1000); // 每秒收集一次
        }
        
        private void CollectMetrics(object state)
        {
            if (isDisposed) return;
            
            try
            {
                // 更新当前进程信息
                currentProcess.Refresh();
                
                // 收集内存使用情况
                CurrentMemoryUsageMB = currentProcess.WorkingSet64 / (1024 * 1024);
                if (CurrentMemoryUsageMB > PeakMemoryUsageMB)
                    PeakMemoryUsageMB = CurrentMemoryUsageMB;
                
                // 收集线程数量
                CurrentThreadCount = currentProcess.Threads.Count;
                if (CurrentThreadCount > PeakThreadCount)
                    PeakThreadCount = CurrentThreadCount;
                
                // 收集句柄数量
                CurrentHandleCount = currentProcess.HandleCount;
                
                // CPU使用率（简化计算）
                CurrentCpuUsage = CalculateCpuUsage();
                if (CurrentCpuUsage > PeakCpuUsage)
                    PeakCpuUsage = CurrentCpuUsage;
                
                // 检查性能警告
                CheckPerformanceAlerts();
                
                // 触发指标更新事件
                OnMetricsUpdated?.Invoke(new PerformanceMetrics
                {
                    CurrentMemoryUsageMB = CurrentMemoryUsageMB,
                    CurrentCpuUsage = CurrentCpuUsage,
                    CurrentThreadCount = CurrentThreadCount,
                    CurrentHandleCount = CurrentHandleCount,
                    PeakMemoryUsageMB = PeakMemoryUsageMB,
                    PeakCpuUsage = PeakCpuUsage,
                    PeakThreadCount = PeakThreadCount,
                    Timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                OnPerformanceAlert?.Invoke($"性能监控异常: {ex.Message}");
            }
        }
        
        private double CalculateCpuUsage()
        {
            try
            {
                // 简化CPU使用率计算
                var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                cpuCounter.NextValue(); // 第一次调用总是返回0
                Thread.Sleep(100); // 等待100ms
                return Math.Round(cpuCounter.NextValue(), 2);
            }
            catch
            {
                return 0.0;
            }
        }
        
        private void CheckPerformanceAlerts()
        {
            // 内存使用警告
            if (CurrentMemoryUsageMB > 500) // 500MB警告
            {
                OnPerformanceAlert?.Invoke($"内存使用过高: {CurrentMemoryUsageMB}MB");
            }
            
            // 线程数量警告
            if (CurrentThreadCount > 100) // 100个线程警告
            {
                OnPerformanceAlert?.Invoke($"线程数量过多: {CurrentThreadCount}");
            }
            
            // 句柄数量警告
            if (CurrentHandleCount > 1000) // 1000个句柄警告
            {
                OnPerformanceAlert?.Invoke($"句柄数量过多: {CurrentHandleCount}");
            }
        }
        
        public void ResetPeakValues()
        {
            PeakMemoryUsageMB = 0;
            PeakCpuUsage = 0;
            PeakThreadCount = 0;
        }
        
        public void Dispose()
        {
            if (!isDisposed)
            {
                isDisposed = true;
                
                // 停止定时器
                monitorTimer?.Change(Timeout.Infinite, Timeout.Infinite);
                monitorTimer?.Dispose();
                
                // 释放进程对象
                currentProcess?.Dispose();
            }
        }
    }
    
    /// <summary>
    /// 性能指标数据
    /// </summary>
    public class PerformanceMetrics
    {
        public long CurrentMemoryUsageMB { get; set; }
        public double CurrentCpuUsage { get; set; }
        public int CurrentThreadCount { get; set; }
        public int CurrentHandleCount { get; set; }
        public long PeakMemoryUsageMB { get; set; }
        public double PeakCpuUsage { get; set; }
        public int PeakThreadCount { get; set; }
        public DateTime Timestamp { get; set; }
    }
}
